<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel - RINT 数据分享平台</title>
    <link href="/static/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="/static/style.css" rel="stylesheet">
    <link rel="icon" type="image/x-icon" href="/static/favicon.ico">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/">RINT 数据分享平台</a>
            <div class="navbar-nav ms-auto" id="navbarNav">
                <!-- Navigation will be updated by JavaScript based on authentication state -->
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>User Management</h2>
                    <button class="btn btn-success" onclick="refreshUsers()">
                        Refresh Users
                    </button>
                </div>
                
                <div class="card">
                    <div class="card-body">
                        <div id="usersTable">
                            <!-- Users table will be loaded here -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Data Management Section -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>Public Data Management</h2>
                    <div>
                        <button class="btn btn-info" onclick="analyzeData()">
                            Analyze Data
                        </button>
                        <button class="btn btn-success" onclick="loadPublicData()">
                            Refresh Data
                        </button>
                    </div>
                </div>
                
                <!-- Analytics Overview -->
                <div class="row mb-4" id="analyticsSection" style="display: none;">
                    <div class="col-md-2">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 id="totalPublicData">-</h5>
                                <p class="card-text">Public Data</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 id="totalStorage">-</h5>
                                <p class="card-text">Storage (MB)</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 id="orphanedCount">-</h5>
                                <p class="card-text">Orphaned</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 id="duplicateCount">-</h5>
                                <p class="card-text">Duplicates</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 id="oldUnusedCount">-</h5>
                                <p class="card-text">Old/Unused</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 id="safeToDeleteCount">-</h5>
                                <p class="card-text">Safe to Delete</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Data Table -->
                <div class="card">
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <select class="form-select" id="statusFilter">
                                    <option value="all">All Public Data</option>
                                    <option value="safe">Safe to Delete (Score > 0.8)</option>
                                    <option value="review">Needs Review (Score 0.5-0.8)</option>
                                    <option value="risky">Risky to Delete (Score < 0.5)</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <input type="text" class="form-control" id="searchData" placeholder="Search data...">
                            </div>
                            <div class="col-md-4">
                                <button class="btn btn-warning" onclick="bulkDeleteSafe()" id="bulkDeleteBtn">
                                    Bulk Delete Safe Items
                                </button>
                            </div>
                        </div>
                        
                        <div id="publicDataTable">
                            <!-- Data table will be loaded here -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Garbage Collection Section -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>Garbage Collection</h2>
                </div>
                
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">清理孤立的 DVC 存储文件</h5>
                        <p class="card-text">
                            垃圾回收将删除 DVC 存储中所有未被数据库引用的文件。这有助于释放存储空间。
                        </p>
                        <div class="d-flex align-items-center">
                            <button class="btn btn-warning" onclick="performGarbageCollection()" id="gcButton">
                                执行垃圾回收
                            </button>
                            <div class="ms-3" id="gcStatus" style="display: none;">
                                <div class="spinner-border spinner-border-sm text-warning" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <span class="ms-2">正在执行垃圾回收...</span>
                            </div>
                        </div>
                        <div id="gcResult" class="mt-3"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Password Reset Modal -->
    <div class="modal fade" id="passwordResetModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Reset User Password</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="passwordResetForm">
                        <div class="mb-3">
                            <label for="resetEmail" class="form-label">User Email</label>
                            <input type="email" class="form-control" id="resetEmail" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="newPassword" class="form-label">New Password</label>
                            <input type="password" class="form-control" id="newPassword" required minlength="8">
                            <div class="form-text">Password must be at least 8 characters long</div>
                        </div>
                        <div class="mb-3">
                            <label for="confirmNewPassword" class="form-label">Confirm New Password</label>
                            <input type="password" class="form-control" id="confirmNewPassword" required minlength="8">
                        </div>
                        <input type="hidden" id="resetUserId">
                        <button type="submit" class="btn btn-primary">Reset Password</button>
                    </form>
                    <div id="passwordResetMessage" class="mt-3"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Confirmation Modal -->
    <div class="modal fade" id="confirmModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmModalTitle">Confirm Action</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="confirmModalBody">
                    Are you sure you want to perform this action?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="confirmModalButton">Confirm</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/bootstrap/bootstrap.bundle.min.js"></script>
    <script>
        let authToken = localStorage.getItem('token');
        let currentUser = null;
        
        if (!authToken) {
            window.location.href = '/login';
        }

        async function loadCurrentUser() {
            try {
                const response = await fetch('/api/user-info', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    currentUser = await response.json();
                    // Update navigation
                    updateNavigation();
                    if (!currentUser.is_admin) {
                        window.location.href = '/dashboard';
                    }
                } else {
                    window.location.href = '/login';
                }
            } catch (error) {
                console.error('Error loading current user:', error);
                window.location.href = '/login';
            }
        }

        function updateNavigation() {
            const navbarNav = document.getElementById('navbarNav');
            
            if (currentUser) {
                // User is logged in
                navbarNav.innerHTML = `
                    <a class="nav-link" href="/dashboard">Dashboard</a>
                    <a class="nav-link active" href="/admin">Admin Panel</a>
                    <div class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <span id="currentUserEmail">${currentUser.email}</span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                            <li><a class="dropdown-item" href="#" onclick="logout()">Logout</a></li>
                        </ul>
                    </div>
                `;
            }
        }

        async function loadUsers() {
            try {
                const response = await fetch('/api/admin/users', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    const response_data = await response.json();
                    const users = response_data.users || response_data; // Handle both paginated and direct array responses
                    displayUsers(users);
                } else {
                    console.error('Failed to load users');
                    document.getElementById('usersTable').innerHTML = '<div class="alert alert-danger">Failed to load users</div>';
                }
            } catch (error) {
                console.error('Error loading users:', error);
                document.getElementById('usersTable').innerHTML = '<div class="alert alert-danger">Network error occurred</div>';
            }
        }

        function displayUsers(users) {
            const container = document.getElementById('usersTable');
            
            if (users.length === 0) {
                container.innerHTML = '<div class="alert alert-info">No users found</div>';
                return;
            }
            
            let html = `
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Email</th>
                            <th>Admin Status</th>
                            <th>Created</th>
<th>Actions</th>
                    </tr>
                </thead>
                <tbody>
            `;
            
            users.forEach(user => {
                const isCurrentUser = user.id === currentUser.id;
                html += `
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.email}</td>
                        <td>
                            <span class="badge ${user.is_admin ? 'bg-success' : 'bg-secondary'}">
                                ${user.is_admin ? 'Admin' : 'User'}
                            </span>
                        </td>
                        <td>${new Date(user.created_at).toLocaleDateString()}</td>
                        <td>
                            ${!isCurrentUser ? `
                                <button class="btn btn-sm ${user.is_admin ? 'btn-warning' : 'btn-primary'}" 
                                        onclick="toggleAdminStatus(${user.id})">
                                    ${user.is_admin ? 'Remove Admin' : 'Make Admin'}
                                </button>
                                <button class="btn btn-sm btn-info" 
                                        onclick="showPasswordResetModal(${user.id}, '${user.email}')">
                                    Reset Password
                                </button>
                                <button class="btn btn-sm btn-danger" 
                                        onclick="confirmDeleteUser(${user.id}, '${user.email}')">
                                    Delete
                                </button>
                            ` : '<span class="text-muted">(You)</span>'}
                        </td>
                    </tr>
                `;
            });
            
            html += `
                    </tbody>
                </table>
            `;
            
            container.innerHTML = html;
        }

        async function toggleAdminStatus(userId) {
            try {
                const response = await fetch(`/api/admin/users/${userId}/toggle-admin`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    loadUsers();
                } else {
                    const error = await response.json();
                    alert(error.detail || 'Failed to toggle admin status');
                }
            } catch (error) {
                console.error('Error toggling admin status:', error);
                alert('Network error occurred');
            }
        }

        function confirmDeleteUser(userId, userEmail) {
            const modal = new bootstrap.Modal(document.getElementById('confirmModal'));
            document.getElementById('confirmModalTitle').textContent = 'Delete User';
            document.getElementById('confirmModalBody').textContent = `Are you sure you want to delete user "${userEmail}"? This action cannot be undone.`;
            
            const confirmButton = document.getElementById('confirmModalButton');
            confirmButton.textContent = 'Delete';
            confirmButton.className = 'btn btn-danger';
            confirmButton.onclick = () => deleteUser(userId);
            
            modal.show();
        }

        async function deleteUser(userId) {
            try {
                const response = await fetch(`/api/admin/users/${userId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('confirmModal')).hide();
                    loadUsers();
                } else {
                    const error = await response.json();
                    alert(error.detail || 'Failed to delete user');
                }
            } catch (error) {
                console.error('Error deleting user:', error);
                alert('Network error occurred');
            }
        }

        function refreshUsers() {
            loadUsers();
        }

        function showPasswordResetModal(userId, userEmail) {
            const modal = new bootstrap.Modal(document.getElementById('passwordResetModal'));
            document.getElementById('resetUserId').value = userId;
            document.getElementById('resetEmail').value = userEmail;
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmNewPassword').value = '';
            document.getElementById('passwordResetMessage').innerHTML = '';
            
            modal.show();
        }

        document.getElementById('passwordResetForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const userId = document.getElementById('resetUserId').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmNewPassword').value;
            const messageDiv = document.getElementById('passwordResetMessage');
            
            if (newPassword !== confirmPassword) {
                messageDiv.innerHTML = '<div class="alert alert-danger">Passwords do not match</div>';
                return;
            }
            
            if (newPassword.length < 8) {
                messageDiv.innerHTML = '<div class="alert alert-danger">Password must be at least 8 characters long</div>';
                return;
            }
            
            try {
                const response = await fetch(`/api/admin/users/${userId}/reset-password`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${authToken}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        new_password: newPassword
                    })
                });
                
                if (response.ok) {
                    messageDiv.innerHTML = '<div class="alert alert-success">Password reset successfully!</div>';
                    setTimeout(() => {
                        bootstrap.Modal.getInstance(document.getElementById('passwordResetModal')).hide();
                    }, 2000);
                } else {
                    const error = await response.json();
                    messageDiv.innerHTML = `<div class="alert alert-danger">${error.detail || 'Failed to reset password'}</div>`;
                }
            } catch (error) {
                messageDiv.innerHTML = '<div class="alert alert-danger">Network error occurred</div>';
            }
        });

        async function performGarbageCollection() {
            const gcButton = document.getElementById('gcButton');
            const gcStatus = document.getElementById('gcStatus');
            const gcResult = document.getElementById('gcResult');
            
            // Show loading state
            gcButton.disabled = true;
            gcStatus.style.display = 'block';
            gcResult.innerHTML = '';
            
            try {
                const response = await fetch('/api/admin/garbage-collect', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    
                    // Format space freed in human readable format
                    const spaceFreedMB = (result.space_freed / (1024 * 1024)).toFixed(2);
                    
                    gcResult.innerHTML = `
                        <div class="alert alert-success">
                            <h6>垃圾回收完成！</h6>
                            <p class="mb-0">
                                <strong>删除文件数:</strong> ${result.files_removed}<br>
                                <strong>释放空间:</strong> ${spaceFreedMB} MB
                            </p>
                        </div>
                    `;
                } else {
                    const error = await response.json();
                    gcResult.innerHTML = `
                        <div class="alert alert-danger">
                            垃圾回收失败: ${error.detail || '未知错误'}
                        </div>
                    `;
                }
            } catch (error) {
                console.error('Error performing garbage collection:', error);
                gcResult.innerHTML = `
                    <div class="alert alert-danger">
                        垃圾回收失败: ${error.message}
                    </div>
                `;
            } finally {
                // Hide loading state
                gcButton.disabled = false;
                gcStatus.style.display = 'none';
            }
        }

        async function loadPublicData() {
            try {
                const response = await fetch('/api/admin/data/public', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    displayPublicData(data);
                } else {
                    console.error('Failed to load public data');
                    document.getElementById('publicDataTable').innerHTML = '<div class="alert alert-danger">Failed to load public data</div>';
                }
            } catch (error) {
                console.error('Error loading public data:', error);
                document.getElementById('publicDataTable').innerHTML = '<div class="alert alert-danger">Network error occurred</div>';
            }
        }

        async function analyzeData() {
            try {
                const response = await fetch('/api/admin/data/analyze', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    const analysis = await response.json();
                    displayAnalytics(analysis);
                } else {
                    console.error('Failed to analyze data');
                    alert('Failed to analyze data');
                }
            } catch (error) {
                console.error('Error analyzing data:', error);
                alert('Network error occurred');
            }
        }

        function displayAnalytics(analysis) {
            document.getElementById('totalPublicData').textContent = analysis.total_public_data;
            document.getElementById('totalStorage').textContent = analysis.total_storage_mb.toFixed(1);
            document.getElementById('orphanedCount').textContent = analysis.orphaned_count;
            document.getElementById('duplicateCount').textContent = analysis.duplicate_count;
            document.getElementById('oldUnusedCount').textContent = analysis.old_unused_count;
            document.getElementById('safeToDeleteCount').textContent = analysis.safe_to_delete_count;
            
            document.getElementById('analyticsSection').style.display = 'flex';
        }

        function displayPublicData(items) {
            const container = document.getElementById('publicDataTable');
            
            if (items.length === 0) {
                container.innerHTML = '<div class="alert alert-info">No public data found</div>';
                return;
            }
            
            let html = `
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Owner</th>
                            <th>Age (days)</th>
                            <th>Size</th>
                            <th>Lineage</th>
                            <th>Safety Score</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            items.forEach(item => {
                const safetyClass = item.safety_score > 0.8 ? 'table-success' : 
                                  item.safety_score > 0.5 ? 'table-warning' : 'table-danger';
                const safetyText = item.safety_score > 0.8 ? 'Safe' : 
                                 item.safety_score > 0.5 ? 'Review' : 'Risky';
                
                html += `
                    <tr class="${safetyClass}">
                        <td>
                            <strong>${item.name}</strong>
                            ${item.project ? `<br><small class="text-muted">${item.project}</small>` : ''}
                        </td>
                        <td>${item.user_email}</td>
                        <td>${item.age_days}</td>
                        <td>${item.file_size ? (item.file_size / 1024 / 1024).toFixed(2) + ' MB' : 'Unknown'}</td>
                        <td>${item.lineage_count}</td>
                        <td>
                            <span class="badge ${item.safety_score > 0.8 ? 'bg-success' : item.safety_score > 0.5 ? 'bg-warning' : 'bg-danger'}">
                                ${safetyText} (${item.safety_score.toFixed(2)})
                            </span>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-danger" onclick="confirmDeleteData(${item.id}, '${item.name.replace(/'/g, "\\'")}')">
                                Delete
                            </button>
                        </td>
                    </tr>
                `;
            });
            
            html += `
                    </tbody>
                </table>
            `;
            
            container.innerHTML = html;
        }

        async function confirmDeleteData(itemId, itemName) {
            if (!confirm(`确定要删除公开数据 "${itemName}" 吗？此操作无法撤销。`)) {
                return;
            }
            
            try {
                const response = await fetch(`/api/admin/data/${itemId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    alert('数据删除成功');
                    loadPublicData();
                } else {
                    const error = await response.json();
                    alert('删除失败: ' + (error.detail || '未知错误'));
                }
            } catch (error) {
                console.error('Error deleting data:', error);
                alert('删除失败: ' + error.message);
            }
        }

        async function bulkDeleteSafe() {
            if (!confirm('确定要批量删除所有安全的公开数据吗？此操作无法撤销。')) {
                return;
            }
            
            const btn = document.getElementById('bulkDeleteBtn');
            btn.disabled = true;
            btn.textContent = 'Deleting...';
            
            try {
                const response = await fetch('/api/admin/data/bulk-delete', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    alert(`批量删除完成！删除了 ${result.files_removed} 个数据项，释放了 ${(result.space_freed / 1024 / 1024).toFixed(2)} MB 空间。`);
                    loadPublicData();
                    analyzeData();
                } else {
                    const error = await response.json();
                    alert('批量删除失败: ' + (error.detail || '未知错误'));
                }
            } catch (error) {
                console.error('Error bulk deleting data:', error);
                alert('批量删除失败: ' + error.message);
            } finally {
                btn.disabled = false;
                btn.textContent = 'Bulk Delete Safe Items';
            }
        }

        function logout() {
            localStorage.removeItem('token');
            // Clear out cookie as well
            document.cookie = 'access_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Strict';
            window.location.href = '/';
        }

        // Initialize the page
        loadCurrentUser().then(() => {
            loadUsers();
            loadPublicData();
        });
    </script>
</body>
</html>